package JVM工作区.优化案例;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: jvmUpdate01
 * @Author: AllenSun
 * @Date: 2022/11/8 下午8:51
 */
public class TestThreadLocalOOM02 {
    public static final Integer SIZE = 500;
    // 5个核心线程，最多线程数5个
    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5, 5, 1,
            TimeUnit.MINUTES, new LinkedBlockingDeque<>());

    // 静态内部类，生命期和线程一致，大小为5M
    static class LocalVariable {//总共有5M
        private byte[] local = new byte[1024 * 1024 * 5];
    }
    // 定义static的ThreadLocal对象
    static ThreadLocal<LocalVariable> local = new ThreadLocal<>();
    public static void main(String[] args) {
        try {
            // 往线程池里放入500个LocalVariable对象，一共2500M
            for (int i = 0; i < SIZE; i++) {
                executor.execute(() -> {
                    // ThreadLocal对象中放入5M数组
                    local.set(new LocalVariable());
                    System.out.println("开始执行");
                });
                Thread.sleep(100);
            }
            local = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
